package com.example.utils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class SRTToMP3Embedder {

//    public static void embedSRTInMP3(File mp3File, File srtFile, File outputMP3File) {
//        try {
//            // 构建 FFmpeg 命令
////            String command = "ffmpeg -i " + mp3File.getPath() + " -i " + srtFile.getPath() + " -c:v copy " + outputMP3File.getPath();
//
//            String command = "ffmpeg -i " + mp3File.getPath() + " -i "+srtFile.getPath()+" -c copy -map 0 -map 1 -metadata:s:s:0 language=eng -metadata:s:s:0 handler_name='Lyrics' "+outputMP3File.getPath();
//            // 执行系统命令
//            Process process = Runtime.getRuntime().exec(command);
//
//            // 等待命令执行完毕并获取退出代码
//            int exitCode = process.waitFor();
//            if (exitCode!= 0) {
//                throw new RuntimeException("FFmpeg 执行失败，退出代码: " + exitCode);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

    private static void embedLrcInMp3(String ffmpegPath, String inputMp3Path, String inputLrcPath, String outputMp3Path) throws IOException {
//        String[] command = {ffmpegPath, "-i", inputMp3Path, "-f lrc -i", inputLrcPath, "-c", "copy", "-map", "0", "-map", "1", "-metadata:s:s:0", "language=eng", "-metadata:s:s:0", "handler_name=Lyrics", "-f mp3",outputMp3Path};
        String[] command = {ffmpegPath, "-i", inputMp3Path, "-f lrc -i", inputLrcPath, "-c", "copy", "-map", "0", "-map", "1", "-metadata:s:s:0", "language=eng", "-metadata:s:s:0", "handler_name=Lyrics", "-f mp3",outputMp3Path};

        for (String element : command) {
            System.out.print(element+" ");
        }
        ProcessBuilder processBuilder = new ProcessBuilder(command);
        Process process = processBuilder.start();

        try {
            int exitCode = process.waitFor();
            if (exitCode != 0) {
                throw new IOException("FFmpeg command execution failed with exit code " + exitCode);
            }
        } catch (InterruptedException e) {
            throw new IOException("FFmpeg command execution interrupted: " + e.getMessage());
        }
    }



//    public static void convertSRTToLRC(String srtFilePath, String lrcFilePath) {
//        try (BufferedReader srtReader = new BufferedReader(new FileReader(srtFilePath));
//            BufferedWriter lrcWriter = new BufferedWriter(new FileWriter(lrcFilePath))) {
//
//            String line;
//            while ((line = srtReader.readLine())!= null) {
//                // 解析 SRT 行并提取时间和文本
//                String[] parts = line.split("=");
//                String time = parts[0].trim();
//                String text = parts[1].trim();
//
//                // 将时间和文本转换为 LRC 格式
//                String lrcTime = time.substring(1, time.length() - 1).replaceAll(":", "");
//                String lrcText = text;
//
//                // 写入 LRC 文件
//                lrcWriter.write(lrcTime + "|" + lrcText + "\n");
//            }
//
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }

    private static void convertSrtToLrc(String srtFilePath, String lrcFilePath) throws IOException {
        try (BufferedReader reader = new BufferedReader(new FileReader(srtFilePath));
            BufferedWriter writer = new BufferedWriter(new FileWriter(lrcFilePath))) {

            String line;
            int lineCount = 0;

            while ((line = reader.readLine()) != null) {
                lineCount++;

                if (lineCount == 1) {
                    // Skip the line number in SRT format
                    continue;
                }

                if (line.isEmpty()) {
                    // Skip empty lines
                    continue;
                }

                if (line.matches("\\d{2}:\\d{2}:\\d{2},\\d{3}.*")) {
                    // Convert SRT timestamp to LRC timestamp
                    String[] parts = line.split(" --> ");
                    String startTime = convertTimestamp(parts[0]);
                    String endTime = convertTimestamp(parts[1]);
                    writer.write("[" + startTime + "]" + "[" + endTime + "]");
                } else {
                    // Write the subtitle text
                    writer.write(line);
                }

                writer.newLine();
            }
        }
    }

    private static String convertTimestamp(String srtTimestamp) {
        // Convert SRT timestamp (hh:mm:ss,mmm) to LRC timestamp (mm:ss.SS)
        String[] parts = srtTimestamp.split(":|,");
        int hours = Integer.parseInt(parts[0]);
        int minutes = Integer.parseInt(parts[1]);
        int seconds = Integer.parseInt(parts[2]);
        int milliseconds = Integer.parseInt(parts[3]);
        int totalSeconds = hours * 3600 + minutes * 60 + seconds;
        int centiseconds = milliseconds / 10;
        return String.format("%02d:%02d.%02d", totalSeconds / 60, totalSeconds % 60, centiseconds);
    }

    public static void main(String[] args) throws IOException{

        String fileNameOnly = "/Users/xiaoxu.wu/Desktop/20220617";

        // 替换为你的 SRT 文件路径
        String srtFilePath = fileNameOnly + ".srt";

        // 替换为你的 LRC 文件路径
        String lrcFilePath = fileNameOnly + ".lrc";
        // 执行转换
        convertSrtToLrc(srtFilePath, lrcFilePath);


        // 替换为你的 MP3 文件路径
        String mp3File = fileNameOnly + ".MP3";
        // 替换为输出的嵌入字幕后的 MP3 文件路径
        String outputMP3File = fileNameOnly+ "-new.mp3";

        // 执行嵌入操作
//        embedSRTInMP3(mp3File, lrcFile, outputMP3File);
        embedLrcInMp3("ffmpeg", mp3File, lrcFilePath, outputMP3File);

    }
}